// 参考：https://www.npmjs.com/package/nodejs-websocket

const port = 8081;
const WebSocket = require("nodejs-websocket");

const ws = WebSocket.createServer((conn) => {
    console.log(`websocket onconnection`);
    conn.on("text", (message) => {
        console.log(`websocket received a message: ${message}`);
        broadcast(message);
    });
    conn.on("close", (code, reason) => {
        console.log(`websocket closed, code: ${code}, reason: ${reason}`);
    });
    conn.on("error", (error) => {
        console.log(`websocket on error: ${error}`);
    });
}).listen(port);

function broadcast(message){
    ws.connections.forEach((conn) => {
        conn.sendText(message);
    });
}